package com.lujianfei.babymilkmemory.compose

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.ExperimentalUnitApi
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.SecureFlagPolicy
import com.lujianfei.babymilkmemory.MyApplication
import com.lujianfei.babymilkmemory.compose.dialog.MyPopupMenu
import com.lujianfei.babymilkmemory.database.table.HistoryTable
import com.lujianfei.babymilkmemory.sp.Setting
import com.lujianfei.babymilkmemory.ui.history.HistoryActivity
import com.lujianfei.babymilkmemory.viewmodel.MainViewModel
import java.util.*

enum class MainComposeType(val label: String) {
    DRINK_MILK("喂奶"),
    PEE("拉粑粑"),
    DIAPER("换尿布");
    companion object {
        fun fromLabel(label: String): MainComposeType {
            return when (label) {
                DRINK_MILK.label -> DRINK_MILK
                PEE.label -> PEE
                DIAPER.label -> DIAPER
                else -> DRINK_MILK
            }
        }
    }
}

@ExperimentalUnitApi
@ExperimentalComposeUiApi
@Composable
fun MainCompose(mainViewModel: MainViewModel, navController: MutableState<MainComposeType>) {
    val alertDialog = remember { mutableStateOf(false) }
    Column(
        modifier = Modifier
            .background(Color.Black)
            .fillMaxWidth()
            .fillMaxHeight()
            .pointerInput(Unit) {
                detectTapGestures(
                    onDoubleTap = {
                        alertDialog.value = true
                    }
                )
            }
    ) {
        // 上次喂奶时间
        LastMilkTime(mainViewModel, alertDialog, navController = navController, mainComposeType = navController.value)
        // 距离上次喂奶时间
        FromLastTime(mainViewModel, mainComposeType = navController.value)
    }
    showDialog(alertDialog, mainViewModel = mainViewModel, mainComposeType = navController.value)
}

/**
 * 展示上次喂奶时间
 */
@ExperimentalComposeUiApi
@ExperimentalUnitApi
@Composable
fun LastMilkTime(
    mainViewModel: MainViewModel,
    alertDialog: MutableState<Boolean>,
    navController: MutableState<MainComposeType>,
    mainComposeType: MainComposeType
) {
    val showPopupMenu = remember { mutableStateOf(false) }
    val context = LocalContext.current
    Box(modifier = Modifier.padding(0.dp)) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Box(modifier = Modifier.padding(start = 35.dp), contentAlignment = Alignment.Center) {
                Column {
                    val textStr = mainComposeType.label + "时间"
                    Text(
                        text = textStr,
                        color = Color.White,
                        fontSize = 40.sp,
                        textAlign = TextAlign.Center,
                    )
                    IconButton(onClick = {
                        HistoryActivity.start(context, type = when (mainComposeType) {
                            MainComposeType.DRINK_MILK -> HistoryTable.Type.Milk
                            MainComposeType.PEE -> HistoryTable.Type.Pee
                            MainComposeType.DIAPER -> HistoryTable.Type.Diaper
                        })
                    }) {
                        Icon(Icons.Default.Info, contentDescription = "", tint = Color.White)
                    }
                }
            }
            Box(contentAlignment = Alignment.CenterStart,modifier = Modifier
                .padding(start = 40.dp)
                .fillMaxWidth()
                .pointerInput(Unit) {
                    detectTapGestures(
                        onLongPress = {
                            showTimePicker(
                                context = context,
                                mainViewModel = mainViewModel,
                                mainComposeType = navController.value
                            )
                        },
                        onDoubleTap = {
                            alertDialog.value = true
                        }
                    )
                }) {
                Text(
                    text = mainViewModel.lastTimeFeedStr ,
                    color = Color.White,
                    fontSize = TextUnit(if (mainComposeType == MainComposeType.PEE) 80f else 160f, TextUnitType.Sp),
                    textAlign = TextAlign.Center
                )
            }
        }
        Box(modifier = Modifier.align(Alignment.TopEnd)) {
            IconButton(onClick = {
                showPopupMenu.value = !showPopupMenu.value
            }) {
                Icon(Icons.Default.Menu, contentDescription = "", tint = Color.White)
            }
            MyPopupMenu(
                menuItems = MainComposeType.values().map { it.label },
                onClickCallbacks =
                {
                    navController.value = MainComposeType.fromLabel(it)
                    Setting.INSTANCE.lastOperationLabel = navController.value.label
                },
                showMenu = showPopupMenu
            ) {
                showPopupMenu.value = false
            }
        }
    }
}

/**
 * 设置喂奶的具体时间
 */
fun showTimePicker(context: Context, mainViewModel: MainViewModel, mainComposeType: MainComposeType) {
    val calendar = Calendar.getInstance()
    val lastTimeFeed = mainViewModel.getLastTimeFeed(mainComposeType)
    if (lastTimeFeed > 0L) {
        calendar.timeInMillis = lastTimeFeed
    }
    val initYear = calendar.get(Calendar.YEAR)
    val initMonth = calendar.get(Calendar.MONTH)
    val initDay = calendar.get(Calendar.DAY_OF_MONTH)
    val initHour = calendar.get(Calendar.HOUR_OF_DAY)
    val initMinute = calendar.get(Calendar.MINUTE)
    when (mainComposeType) {
        MainComposeType.DRINK_MILK, MainComposeType.DIAPER -> {
            val timePickerDialog = TimePickerDialog(context,
                {_, hour : Int, minute: Int ->
                    calendar.set(Calendar.HOUR_OF_DAY, hour)
                    calendar.set(Calendar.MINUTE, minute)
                    mainViewModel.updateLastTimeFeedTo(milliSec = calendar.timeInMillis, mainComposeType = mainComposeType)
                }, initHour, initMinute, false
            )
            timePickerDialog.show()
        }
        MainComposeType.PEE -> {
            val datePickerDialog = DatePickerDialog(context,
                { view, year, month, dayOfMonth ->
                    calendar.set(Calendar.YEAR, year)
                    calendar.set(Calendar.MONTH, month)
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                    val timePickerDialog = TimePickerDialog(context,
                        {_, hour : Int, minute: Int ->
                            calendar.set(Calendar.HOUR_OF_DAY, hour)
                            calendar.set(Calendar.MINUTE, minute)
                            mainViewModel.updateLastTimeFeedTo(milliSec = calendar.timeInMillis, mainComposeType = mainComposeType)
                        }, initHour, initMinute, false
                    )
                    timePickerDialog.show()
                },
                initYear,
                initMonth,
                initDay
            )
            datePickerDialog.show()
        }
    }
}

/**
 * 展示距离上次喂奶时间
 */
@ExperimentalComposeUiApi
@ExperimentalUnitApi
@Composable
fun FromLastTime(mainViewModel: MainViewModel, mainComposeType: MainComposeType) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Box(modifier = Modifier.padding(start = 35.dp), contentAlignment = Alignment.Center) {
            Text(
                text = "已经\n过了",
                color = Color.White,
                fontSize = TextUnit(40f, TextUnitType.Sp),
                textAlign = TextAlign.Center
            )
        }
        Box(modifier = Modifier.padding(start = 50.dp), contentAlignment = Alignment.Center) {
            Text(
                text = mainViewModel.differBetweenLastTimeFeedStr ,
                color = Color.White,
                fontSize = TextUnit(if (mainComposeType == MainComposeType.PEE) 50f else 70f, TextUnitType.Sp),
                textAlign = TextAlign.Center
            )
        }
    }
}


@ExperimentalUnitApi
@ExperimentalComposeUiApi
@Composable
private fun showDialog(
    alertDialog: MutableState<Boolean>,
    mainViewModel: MainViewModel,
    mainComposeType: MainComposeType
) {
    if (alertDialog.value) {
        AlertDialog(
            //当用户尝试通过单击外部或按下后退按钮来关闭对话框时执行。单击关闭按钮时不会调用此方法。
            onDismissRequest = {
                alertDialog.value = false
            },
            //显示有关对话框目的的详细信息的文本。提供的文本样式默认为 Typography.body1
            text = {
                Text(
                    "确认更新${mainComposeType.label}时间？",fontSize = TextUnit(30f, TextUnitType.Sp),
                    color = Color.Black
                )
            },
            //一个按钮，用于确认的操作，从而解决触发对话框的原因。该对话框不会为此按钮设置任何事件，因此它们需要由调用者设置。null则不显示
            confirmButton = {
                TextButton(
                    onClick = {
                        mainViewModel.updateLastTimeFeed(mainComposeType)
                        alertDialog.value = false
                    }
                ) {
                    Text("确认", fontSize = TextUnit(28f, TextUnitType.Sp))
                }
            },
            //用于关闭对话框的按钮。该对话框不会为此按钮设置任何事件，因此它们需要由调用者设置,null则不显示
            dismissButton = {
                TextButton(
                    onClick = {
                        alertDialog.value = false
                    },
                    colors = ButtonDefaults.textButtonColors(contentColor = Color.Gray)
                ) {
                    Text("取消", fontSize = TextUnit(28f, TextUnitType.Sp))
                }
            },
            //对话框的背景颜色
            containerColor = Color.White,
            //此对话框为其子级提供的首选内容颜色。
            textContentColor = Color.Black,
            titleContentColor = Color.Black,
            //平台特定的属性，以进一步配置对话框
            properties = DialogProperties(
                //是否可以通过按下后退按钮来关闭对话框。 如果为 true，按下后退按钮将调用 onDismissRequest。
                dismissOnBackPress = true,
                //是否可以通过在对话框边界外单击来关闭对话框。 如果为 true，单击对话框外将调用 onDismissRequest
                dismissOnClickOutside = true,
                //用于在对话框窗口上设置 WindowManager.LayoutParams.FLAG_SECURE 的策略。
                securePolicy = SecureFlagPolicy.Inherit,
                //对话框内容的宽度是否应限制为平台默认值，小于屏幕宽度。
                usePlatformDefaultWidth = false
            )
        )
    }
}